#!/bin/bash
set -o errexit -o pipefail -o noclobber -o nounset

REPORT_RESULT_OUTPUTFILE="$TMT_TEST_DATA/tmt-report-results.yaml"
outputFile=
help=False

die() { echo "$*" >&2; exit 2; }  # complain to STDERR and exit with error
needs_arg() { if [ -z "$OPTARG" ]; then die "No arg for --$OPT option"; fi; }

write_report_file () {
    echo "  - name: \"${TESTNAME}\"" >> "$REPORT_RESULT_OUTPUTFILE"
    echo "    result: \"${TESTRESULT}\"" >> "$REPORT_RESULT_OUTPUTFILE"
    if [ -n "${outputFile}" ]; then
        # FIXME: The UNIX filenames can contain double quotes in the filename
        #       (`$outputFile`). We should escape them as well as for TESTNAME.
        #       Otherwise, the resulting YAML file can be invalid.
        echo "    log:" >> "$REPORT_RESULT_OUTPUTFILE"
        echo "      - \"${outputFile}\"" >> "$REPORT_RESULT_OUTPUTFILE"
    fi
    echo "    end-time: \"$(date --utc +%FT%T.%6N%:z)\"" >> "$REPORT_RESULT_OUTPUTFILE"
}

copy_outputfile_to_data_dir () {
    filename=$(echo "$outputFile" | awk -F/ '{print $NF}')
    # Replace slashes in test name with underscores.
    fileprefix=$(echo "$TESTNAME" | tr / _ | tr ' ' _)
    # Cut first char if underscore.
    [[ ${fileprefix:0:1} == '_' ]] && fileprefix=$(echo "$fileprefix" | cut -c 2-)
    # Copy outputfile to data dir. Prefix with underscored test name.
    cp -f "$outputFile" "${TMT_TEST_DATA}/${fileprefix}_${filename}"
    # Make sure that the log file is readable for guest.pull()
    chmod a+r "${TMT_TEST_DATA}/${fileprefix}_${filename}"
    outputFile="$fileprefix"_"$filename"
}

position=
check_opt_args () {
    local OPTIND
    while getopts s:o:p:t:port:message:outputfile:help-: OPT; do
	# support long options: https://stackoverflow.com/a/28466267/519360
        if [ "$OPT" = "-" ]; then   # long option: reformulate OPT and OPTARG
            OPT="${OPTARG%%=*}"       # extract long option name
        fi
        case "$OPT" in
            server )         needs_arg; OPTIND=$((OPTIND+1)) ;;
            s )              needs_arg; ;;
            outputfile )     needs_arg; eval "outputFile=\"\$$OPTIND\"" ; OPTIND=$((OPTIND+1)) ;;
            o )              needs_arg; outputFile="$OPTARG" ;;
            p )              needs_arg; ;;
            disable-plugin ) needs_arg; OPTIND=$((OPTIND+1)) ;;
            t )              needs_arg; ;;
            message )        needs_arg; OPTIND=$((OPTIND+1)) ;;
            port )           needs_arg; OPTIND=$((OPTIND+1)) ;;
            no-plugins )     ;;
            help )           help=True ;;
            ??* )            die "Illegal option --$OPT" ;;  # bad long option
            ? )              exit 2 ;;  # bad short option (error reported via getopts)
        esac
    done
    shift $((OPTIND-1)) # remove parsed options and args from $@ list
    position=$((OPTIND-1))
}
# Options wrapped in quotes to ensure -t/--message argument is parsed as a string phrase
# rather than just the first string until a whitespace is encountered.
check_opt_args "$@"
shift $position # remove parsed options and args from $@ list
# Return help options when command issued with no options or arguments.
if [ $# -lt 2 ] || [ $help == True ]; then
    echo "Usage:"
    echo "  rstrnt-report-result [OPTION?] TASK_PATH RESULT [SCORE]"
    echo ""
    echo "Report results to lab controller. if you don't specify --port or"
    echo "the server url you must have RECIPE_URL and TASKID defined."
    echo "If HARNESS_PREFIX is defined then the value of that must be"
    echo "prefixed to RECIPE_URL and TASKID"
    echo ""
    echo "Help Options:"
    echo "  -h, --help                      Show help options"
    echo ""
    echo "Application Options:"
    echo "  --port=PORT                     This option is ignored by tmt."
    echo "  -s, --server=URL                This option is ignored by tmt."
    echo "  -t, --message=TEXT              This option is ignored by tmt."
    echo "  -o, --outputfile=FILE           Log to upload with result, \$OUTPUTFILE is used by default"
    echo "  -p, --disable-plugin=PLUGIN     This option is ignored by tmt."
    echo "  --no-plugins                    This option is ignored by tmt."
    echo ""
    exit 1
fi

TESTNAME=$1
# If test name contains double quotes, escape them with a backslash
TESTNAME=${TESTNAME//\"/\\\"}
# If last character is a ':' then delete it.
[[ ${TESTNAME: -1} == ':' ]] && TESTNAME=${TESTNAME::-1}
# If the first character isn't a '/' then add it.
[[ ${TESTNAME:0:1} != '/' ]] && TESTNAME=/$TESTNAME
# If TESTNAME is just / then set it to the parent test name.
[[ $TESTNAME = "/" ]] && TESTNAME=$TMT_TEST_NAME
TESTRESULT=$(echo "$2" | tr '[:upper:]' '[:lower:]')

if [[ "$0" == *"rhts-report-result"* ]]; then
    outputFile=$3
    copy_outputfile_to_data_dir
    write_report_file
    exit 0
fi
shift 2 #$((OPTIND-1)) # remove parsed options and args from $@ list
if [ $# -gt 0 ];then
    check_opt_args "$@"
fi

[ -n "$outputFile" ] && copy_outputfile_to_data_dir
write_report_file
